package org.jeecg.modules.demo.hd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.hd.entity.AppGoods;
import org.jeecg.modules.demo.hd.entity.AppUserGoods;
import org.jeecg.modules.demo.hd.mapper.AppGoodsMapper;
import org.jeecg.modules.demo.hd.mapper.AppUserGoodsMapper;
import org.jeecg.modules.demo.hd.service.IAppUserGoodsService;
import org.jeecg.modules.demo.hd.vo.usergoods.addUserGoodsVo;
import org.jeecg.modules.demo.hd.vo.usergoods.userGoodsListVo;
import org.jeecg.modules.demo.hd.vo.usergoods.userGoodsModelVo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Description: 用户商品关联表
 * @Author: sutao
 * @Date: 2025-01-19
 * @Version: V1.0
 */
@Service
public class AppUserGoodsServiceImpl extends ServiceImpl<AppUserGoodsMapper, AppUserGoods> implements IAppUserGoodsService {

    @Resource
    private AppGoodsMapper goodsMapper;
    @Resource
    private ISysUserService sysUserService;

    @Override
    @Transactional
    public boolean addUserGoods(addUserGoodsVo vo) {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = currentUser.getId();
        SysUser user = sysUserService.getUserByName(currentUser.getUsername());
        AppGoods appGoods = goodsMapper.selectById(vo.getGoodsId());
        if (appGoods != null) {
            // 查询用户有没有正在领养的
            int userLevel=1;
            if(ObjectUtils.isNotNull(user.getUserLevel() ))
            {
                userLevel=user.getUserLevel();
            }
            if (!checkUserIdAndGoods(userId) && userLevel>= appGoods.getGoodsLevel()) {
                Integer inventoryNum = appGoods.getInventoryNum();
                if (inventoryNum > 0) {
                    AppUserGoods model = new AppUserGoods();
                    model.setGoodsId(vo.getGoodsId());
                    model.setUserId(userId);
                    model.setGoodsName(appGoods.getName());
                    model.setGoodsStatus("1");
                    model.setStartTime(new Date());
                    LocalDate today = LocalDate.now(); // 获取当前日期
                    LocalDate fifteenDaysLater = today.plusDays(appGoods.getPeriodDay()); // 在当前日期基础上加15天
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String formattedDate = fifteenDaysLater.format(formatter);
                    model.setPeriodDay(appGoods.getPeriodDay());
                    model.setEndTime(DateUtils.parseDatetime(formattedDate));
                    this.baseMapper.insert(model);
                    appGoods.setInventoryNum(inventoryNum - 1);
                    this.goodsMapper.updateById(appGoods);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public userGoodsModelVo getCurrentGoods() {
        QueryWrapper<AppUserGoods> queryWrapper = new QueryWrapper<>();
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = currentUser.getId();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("goods_status", 1);
        List<userGoodsListVo> appUserGoods = baseMapper.queryUserGoods(userId);
        Optional<userGoodsListVo> first = appUserGoods.stream().filter(x -> x.getGoodsStatus().equals("1")).findFirst();
        if (first.isPresent()) {
            userGoodsModelVo vo = new userGoodsModelVo();
            BeanUtils.copyProperties(first.get(), vo);
            return vo;
        }
        return null;
    }


    @Override
    public boolean endUserGooods() {
        QueryWrapper<AppUserGoods> queryWrapper = new QueryWrapper<>();
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = currentUser.getId();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("goods_status", 1);
        List<AppUserGoods> appUserGoods = baseMapper.selectList(queryWrapper);
        Optional<AppUserGoods> first = appUserGoods.stream().filter(x -> x.getGoodsStatus().equals("1")).findFirst();
        if (first.isPresent()) {
            AppUserGoods good = first.get();
            good.setGoodsStatus("2");
            baseMapper.updateById(good);
            return true;
        }
        return false;
    }

    @Override
    public List<userGoodsListVo> queryUserGoods(String userId) {
        return baseMapper.queryUserGoods(userId);
    }


    /**
     * 判断用户是否拥有该商品
     *
     * @param userId 用户ID
     * @return true 拥有，false 没有
     */
    private boolean checkUserIdAndGoods(String userId) {
        QueryWrapper<AppUserGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("goods_status", 1);
        int count = this.baseMapper.selectCount(queryWrapper).intValue();
        return count > 0;
    }
}
